const mongoose = require("mongoose");
const ProductMasterSchema = mongoose.model("ProductMasterSchema");
const ProductSchema = mongoose.model("ProductSchema");
const AMZSellerAccountModel = mongoose.model("AMZSellerAccountSchema");
const PTSellerAccountModel = mongoose.model("PTSellerAccountSchema");
const NewProductsModel = mongoose.model("NewProductsSchema");
const ProductTypeDataFieldsModel = mongoose.model(
  "ProductTypeDataFieldsSchema"
);
const AMZFeedHistoryModel = mongoose.model("AMZFeedHistorySchema");
const config = require('../../config/config.local');
const feedsService = require("../service/feeds.service");

let d = {};
d.initMockData = async function () {
  const productMaster = new ProductMasterSchema({
    _id: mongoose.Types.ObjectId("5f8a5189f3b6aa46dc53f0e4"),
    batchId: "batch002",
    previousBatchId: "batch001",
    asin: "1887460217",
    sku: "200",
    ptSellerAccountId: "AIFG0GYW73CJ6",
    ptSellerAccountStoreId: "US_Store1",
    approvalLog: [
      {
        approver: "approver1",
        comments: "comments1",
        date: Date.now(),
        isApproved: true,
      },
      {
        approver: "approver2",
        comments: "comments2",
        date: Date.now(),
        isApproved: true,
      },
      {
        approver: "approver3",
        comments: "comments3",
        date: Date.now(),
        isApproved: true,
      },
    ],
    amazonSubmissionLog: "amazonSubmissionLog1",
    listingStatus: "Draft",
    state: "state1",
    creationDateTime: Date.now(),
    lastModifiedDateTime: Date.now(),
  });
  const r0 = await mongoose.connection.db
    .dropCollection("ProductMasters")
    .catch((err) => {
      console.error(err);
    });
  const r1 = await ProductMasterSchema.insertMany([productMaster]);

  const product1 = new ProductSchema({
    productMetadata: {
      masterId: "5f8a5189f3b6aa46dc53f0e4",
      version: 0,
    },
    sku: "sku001",
    itemType: "itemType_test",
  });
  const product2 = new ProductSchema({
    productMetadata: {
      masterId: "5f8a5189f3b6aa46dc53f0e4",
      version: 1,
    },
    sku: "sku002",
    itemType: "itemType_test",
  });

  const s0 = await mongoose.connection.db
    .dropCollection("Products")
    .catch((err) => {
      console.error(err);
    });
  const s1 = await ProductSchema.insertMany([product1, product2]);
};

d.findProductMasterById = async function (masterId) {
  return await ProductMasterSchema.findById(masterId).lean();
};

d.findProductChanged = async function (masterId) {
  const productMaster = await ProductMasterSchema.findById(masterId).lean();
  const previousBatchId = productMaster.previousBatchId;
  const products = await ProductSchema.find({
    "productMetadata.masterId": "5f8a5189f3b6aa46dc53f0e4",
  }).lean();
};

d.findAmzSellerAccountBySellId = async function (sellerId) {
  let amzSellerAccounts =  await AMZSellerAccountModel.find({
    sellerId: sellerId,
  }).lean();

  return amzSellerAccounts[0];
};

d.findptSellerAccountBySellerId = async function (sellerId) {
  var sellerAccount = await PTSellerAccountModel.find({
    "amzSellerAccountList.amzSellerAccount.sellerId": sellerId,
  }).lean();
  var marketPlaceId;
  var sellerAccountList = sellerAccount[0].amzSellerAccountList;
  for (let i = 0; i < sellerAccountList.length; i++) {
    if (sellerAccountList[i].amzSellerAccount.sellerId == sellerId) {
      marketPlaceId = sellerAccountList[i].amzSellerAccount.marketPlaceId;
    }
  }

  return marketPlaceId;
};

d.findSellIdByStoreId = async function (storeId) {
  var sellerAccount = await PTSellerAccountModel.find({
    "amzSellerAccountList.storeId": mongoose.Types.ObjectId(storeId),
    // "amzSellerAccountList": {
    //   $elemMatch: {
    //     "storeId": mongoose.Types.ObjectId(storeId)
    //   }
    // }
  }).lean();
  var amzSellerAccount;
  var sellerAccountList = sellerAccount[0].amzSellerAccountList;
  for (let i = 0; i < sellerAccountList.length; i++) {
    if (sellerAccountList[i].storeId == storeId) {
      amzSellerAccount = sellerAccountList[i].amzSellerAccount;
    }
  }

  return amzSellerAccount;
};

d.updateFeedSubmissionStatus = async function (
  storeId,
  productIds,
  amzReturn,
  feedProductList
) {
  // FeedSubmissionId: '50148018629',
  //   FeedAmazonType: '_POST_FLAT_FILE_LISTINGS_DATA_',
  //   FeedType: 'LST',
  //   SubmittedDate: '2021-01-02T02:26:52+00:00',
  //   FeedProcessingStatus: '_SUBMITTED_'
  let status = amzReturn.FeedProcessingStatus;
  if (amzReturn.FeedProcessingStatus == "_SUBMITTED_"){
    status = 'FeedSubmitted'
  }

  //update admnewProducts table
  await NewProductsModel.updateMany(
    {
      _id: {
        $in: productIds,
      },
      ptSellerAccount_StoreId: storeId,
    },
    {
      $set: {
        UpdateStage: status,
      },
    }
  );
  //insert into AMZFeedHistory table
  var amzFeedHistory = {
    FeedSubmissionId: amzReturn.FeedSubmissionId,
    ptSellerAccount_storeId: storeId,
    FeedProductList: feedProductList,
    FeedSubmissionLog: {
      SubmissionDateTime: amzReturn.SubmittedDate,
      FeedSubType: amzReturn.FeedType,
      SubmissionStatus: status,
    },
    FeedResponseLog: [
      {
        ResponseDateTime: "",
        sku:"",
        FeedProcessionStatus: "",
        Message: "",
      },
    ],
  };
  await AMZFeedHistoryModel.insertMany([amzFeedHistory]);
};

d.updateFeedSubmissionStatusForCallBack = async function (context, option) {
  //update admnewProducts table
  var amzFeedHistory = await AMZFeedHistoryModel.find({
    FeedSubmissionId: option.submissionId,
  });

  let productIdsForAccepted = [];
  let productIdsForRejected = [];
  let skuForAccepted = [];
  amzFeedHistory[0].FeedProductList.forEach((element) => {
    let bFind = false;
    if (option.skus) {
      for (i = 0; i < option.skus.length; i++) {
        if (option.skus[i] == element.item_sku) {
          bFind = true;
          continue;
        }
      }
    }
    if (!bFind) {//sku feed successed
      productIdsForAccepted.push({
       productId: element.product_id,
       sku: element.item_sku,
       asin: '',
      });
      option.feedResponseLog.push({
        sku: element.item_sku,
        FeedProcessionStatus: 'Success'
      });
      skuForAccepted.push(element.item_sku);
    } else {//sku feed failed
      productIdsForRejected.push(element.product_id);
    }
  });

  if (productIdsForAccepted.length > 0) {
    if (skuForAccepted.length > 0) {
      let marketPlaceId = await this.findptSellerAccountBySellerId(context.sellerId);
      let skuAsinPair = await feedsService.handleFeedCallbackAfterSuccess(context, {
        idList: skuForAccepted,
        marketPlaceId: marketPlaceId
      });

      productIdsForAccepted.forEach(item => {
        for (const pair of skuAsinPair) {
          if (pair.id === item.sku) {
            item.asin = pair.asin
          }
        }
      })
    }

    productIdsForAccepted.forEach(async(item) => {
      await NewProductsModel.updateMany({
        _id: {
          $in: item.productId,
        },
      }, {
        $set: {
          UpdateStage: "FeedAccepted",
          ASIN: item.asin,
        },
      });
    })
    console.log('update asin is done')
  }
  if (productIdsForRejected.length > 0) {
    await NewProductsModel.updateMany(
      {
        _id: {
          $in: productIdsForRejected,
        },
      },
      {
        $set: {
          UpdateStage: "FeedRejected",
        },
      }
    );
  }
  
  //update AMZFeedHistoryModel table
  if (option.feedResponseLog.length > 0) {
    await AMZFeedHistoryModel.updateMany(
      {
        FeedSubmissionId: option.submissionId,
      },
      {
        $set: {
          FeedResponseLog: option.feedResponseLog,
        },
      }
    );
  }
};

function toObjectId(ids) {
  if (ids.constructor === Array) {
    return ids.map(mongoose.Types.ObjectId);
  }
  return mongoose.Types.ObjectId(ids);
}
d.extractProductFeedByproductIds = async function (feedSubType, productIds) {
  let idsparas = toObjectId(productIds);
  var products = await NewProductsModel.aggregate([
    {
      $match: {
        _id: {
          $in: idsparas,
        }
      }
    },
    {
      $lookup: {
        from: "productTypeDataFields",
        localField: "Product.feed_product_type",
        foreignField: "ProductType",
        as: "datafields",
      }
    },
    {
      $project: {
        _id: true,
        Version: true,
        Product: true,
        "datafields.GroupList": true,
      }
    },
  ]);
  var feedProductList = [];
  var productDetails = [];
  var sku;
  // console.log(products);
  if (feedSubType == "COMB") {
    for (let i = 0; i < products.length; i++) {
      var groupList = products[i].datafields[0].GroupList;
      var fields = {};
      groupList.forEach((g) => {
        if (g.GroupName != "Images") {
          for (let j = 0; j < g.FieldList.length; j++) {
            if (products[i].Product[g.FieldList[j].FieldName])
              fields[g.FieldList[j].FieldName] =
                products[i].Product[g.FieldList[j].FieldName];
            //get item_sku
            if (
              g.FieldList[j].FieldName == "item_sku" &&
              products[i].Product[g.FieldList[j].FieldName]
            ) {
              sku = products[i].Product[g.FieldList[j].FieldName];
            }
          }
        } else {
          for (let j = 0; j < g.FieldList.length; j++) {
            if (
              // g.FieldList[j].FieldName == "swatch_image_url" &&
              products[i].Product[g.FieldList[j].FieldName]
            ) {
              //baseAddress + relativeAddress
              fields[g.FieldList[j].FieldName] = config.api_imageurl + "/" + products[i]._id + "/" + products[i].Product[g.FieldList[j].FieldName];
            }
          }
        }
      });
      productDetails.push(fields);
      feedProductList.push({
        product_id: products[i]._id,
        item_sku: sku,
        version: products[i].Version,
      });
      //  console.log(fields);
    }
  } else if (feedSubType == "LST") {
    for (let i = 0; i < products.length; i++) {
      var groupList = products[i].datafields[0].GroupList;
      var fields = {};
      groupList.forEach((g) => {
        if (g.GroupName != "Images") {
          for (let j = 0; j < g.FieldList.length; j++) {
            if (products[i].Product[g.FieldList[j].FieldName])
              fields[g.FieldList[j].FieldName] =
                products[i].Product[g.FieldList[j].FieldName];
            //get item_sku
            if (
              g.FieldList[j].FieldName == "item_sku" &&
              products[i].Product[g.FieldList[j].FieldName]
            ) {
              sku = products[i].Product[g.FieldList[j].FieldName];
            }
          }
        } else {
          for (let j = 0; j < g.FieldList.length; j++) {
            if (
              // g.FieldList[j].FieldName == "swatch_image_url" &&
              products[i].Product[g.FieldList[j].FieldName]
            ) {
                fields[g.FieldList[j].FieldName] = config.api_imageurl + "/" + products[i].Product[g.FieldList[j].FieldName];
            }
          }
        }
      });
      productDetails.push(fields);
      feedProductList.push({
        product_id: products[i]._id,
        item_sku: sku,
        version: products[i].Version,
      });
    }
    //  console.log(fields);
  } else if (feedSubType == "INV") {
    for (let i = 0; i < products.length; i++) {
      var groupList = products[i].datafields[0].GroupList;
      var fields = {};
      groupList.forEach((g) => {
        if (g.GroupName != "Images") {
          for (let j = 0; j < g.FieldList.length; j++) {
            if (products[i].Product[g.FieldList[j].FieldName])
              fields[g.FieldList[j].FieldName] =
                products[i].Product[g.FieldList[j].FieldName];
            //get item_sku
            if (
              g.FieldList[j].FieldName == "item_sku" &&
              products[i].Product[g.FieldList[j].FieldName]
            ) {
              sku = products[i].Product[g.FieldList[j].FieldName];
            }
          }
        } else {
          for (let j = 0; j < g.FieldList.length; j++) {
            if (
              // g.FieldList[j].FieldName == "swatch_image_url" &&
              products[i].Product[g.FieldList[j].FieldName]
            ) {
              fields[g.FieldList[j].FieldName] =
                products[i].Product[g.FieldList[j].FieldName];
            }
          }
        }
      });
      productDetails.push(fields);
      feedProductList.push({
        product_id: products[i]._id,
        item_sku: sku,
        version: products[i].Version,
      });
      //  console.log(fields);
    }
  }
  return {
    productDetails,
    feedProductList,
  };
};

// d.initMockData = initMockData;
// d.findProductMasterById = findProductMasterById;
// d.findProductChanged = findProductChanged;
// d.findAmzSellerAccountBySellId = findAmzSellerAccountBySellId;
// d.findSellIdByStoreId = findSellIdByStoreId;
// d.updateFeedSubmissionStatus = updateFeedSubmissionStatus;
// d.extractProductFeedByproductIds = extractProductFeedByproductIds;

module.exports = d;
